package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 130. 被围绕的区域
 * @date 2025/5/25 11:37
 */
public class E130 {

    /**
     * 方向数组
     */
    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    /**
     * 沿着周边的'O'进行dfs
     *
     * @param board 矩阵
     */
    public void solve(char[][] board) {
        int n = board.length, m = board[0].length;
        // 处理上下边界
        for (int j = 0; j < m; j++) {
            if (board[0][j] == 'O')
                dfs(board, 0, j);
            if (board[n - 1][j] == 'O')
                dfs(board, n - 1, j);
        }
        // 处理左右边界（跳过角点，因为它们已经被上下边界处理过）
        for (int i = 1; i < n - 1; i++) {
            if (board[i][0] == 'O')
                dfs(board, i, 0);
            if (board[i][m - 1] == 'O')
                dfs(board, i, m - 1);
        }
        // 转换矩阵
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                if (board[i][j] == 'T')
                    board[i][j] = 'O';
            }
        }
    }

    /**
     * dfs
     *
     * @param board 矩阵
     * @param i     行
     * @param j     列
     */
    private void dfs(char[][] board, int i, int j) {
        if (i < 0 || i >= board.length ||
                j < 0 || j >= board[0].length || board[i][j] != 'O') {
            return;
        }
        board[i][j] = 'T';
        // 使用循环处理四个方向
        for (int[] dir : directions) {
            dfs(board, i + dir[0], j + dir[1]);
        }
    }
}
